 var percent;
 var flag = true;
$(function () {
	
	$('.fileupload').each(function () {
		uploadImage(this);
	  });
});

function uploadImage(obj){
		var uploaderID = $(obj).attr("data-uploaderid");
		var uploader_key = $("#uploaded-files_"+uploaderID).attr('data-key');
		var page = $('#pageInfo').attr("data-pageId");
	    $(obj).fileupload({
        dataType: 'json',
        formData: {key: uploader_key,pageId :page},
        limitMultiFileUploads: 1,
        
        start: function (e) {
        	$('#progress_'+$(obj).attr("data-uploaderid")).css('display','block');
        },
        
        done: function (e, data) {
        	uploaderID = $(obj).attr("data-uploaderid");
        	var form = $("#imageForm_"+uploaderID);
        	var itemId = $(form).find('input[name="id"]').val();
        	//if(!itemId){//if i'm editing don't clear form
        	//refreshFormData(form);
        	//}
        	
        	$("#error_msj_"+uploaderID).html("");
        	
        	if(data.result[0].hasOwnProperty("error")){
        		$("#error_msj_"+uploaderID).html(data.result[0].error);    		
        		flag = false;
        		return false;
        	}
        	      
        	var img = 0;
        	var maxWidth = 0;
            var maxHeight = 0;
            var type = $("#uploaded-files_"+uploaderID).attr('data-type');
            $("#uploaded-files_"+uploaderID).html("");
            $.each(data.result, function (index, file) {  
            	img=file;
            	
            		$("#uploaded-files_"+uploaderID).append($('<div/>').html("<div id='cropDiv_"+uploaderID+"' class='cropDiv'><img src='/userimages/"+file.websiteId+"/"+file.fileName+"' id='target_"+uploaderID+"' width='100%'/></div>"));
            	if(type != 'gallery'){          	        	                                  	         	           	
            		$("#uploaded-files_"+uploaderID).append($('<div/>').html("<button type='button' class='btn btn-default sendCrop' data-uploaderid='"+uploaderID+"'><i class='general foundicon-photo'></i> Recortar</button>"));
            	}
                
            		
             
                if(index == (data.result.length-1)){
            	   maxWidth  = file.finalWidth;           
            	   maxHeight = file.finalHeight;
               }
            
            }); 
           
            var divWidth = $('.cropDiv').width();
            var imgWidth = img.width;
            percent = divWidth*100/imgWidth;
            var selectorX1 = 100;
            var selectorY1 = 100;
            var selectorX2 = percent*maxWidth/100;
            var selectorY2 = percent*maxHeight/100;
            $('#target_'+uploaderID).Jcrop({
                onSelect: saveCoords,
                onChange: saveCoords,
    			aspectRatio: maxWidth/maxHeight,
    			setSelect: [ selectorX1, selectorY1, selectorX1+selectorX2, selectorY1+selectorY2 ],
    			//maxSize : [ selectorX2, selectorY2],
    			minSize : [ selectorX2, selectorY2]
            });
        
        },
 
        progressall: function (e, data) {
        	if(flag){
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress_'+$(obj).attr("data-uploaderid")+' .bar').css(
                'width',
                progress + '%'
            );
        }
        },
        
        dropZone: $('#dropzone_'+uploaderID),
        
        fail:function (e, data) {
        	alert(data.errorThrown);
        }
     });
 
}


var x,y,x2,y2;
function saveCoords(c)
{
    // variables can be accessed here as
    // c.x, c.y, c.x2, c.y2, c.w, c.h
	 
	  x = 100*c.x/percent;
	  y = 100*c.y/percent;
	  x2 = 100*c.x2/percent;
	  y2 = 100*c.y2/percent;
	
};


//function for load crop and image form data
$('.sendCrop').live("click", function(){
	   
		var uploaderID = $(this).attr("data-uploaderid");
		var form = $("#imageForm_"+uploaderID);
	    var itemId = $(form).find('input[name="id"]').val();
	    var type = $("#uploaded-files_"+uploaderID).attr('data-type');
	    var key = $("#uploaded-files_"+uploaderID).attr('data-key');
	    var page = $('#pageInfo').attr("data-pageId");
	    var cropJson  = new Object();
	    var newImage = $("#cropDiv_"+uploaderID).attr("class");
	    
	    if(type =='header_gal' || type =='gallery'){
	    	
	    	var form_data = $(form).serializeArray();
	    	
	    	$.each(form_data, function(i, field){	
	    		cropJson[field.name] = field.value;
	    	  });
	         }
	    if($(form).attr("data-formtype") == "imageForm" && itemId && !newImage){//edito solo form
	    	updateImageData(form,cropJson,uploaderID);
	    }else if($(form).attr("data-formtype") == "archiveForm" && itemId && !newImage){//edito solo form
	    	updateArchiveData(form,cropJson,uploaderID);
	    }else{//edito o agrego nueva imagen + form
	    if(key =="dataType" || key =="archive"){
	    cropJson.itemID = uploaderID;		
	    }
	    cropJson.key = key;
	    cropJson.pageId = page;
	    cropJson.cropx1 = Math.round(x);
	    cropJson.cropy1 = Math.round(y);
	    cropJson.cropx2 = Math.round(x2);
	    cropJson.cropy2 = Math.round(y2);
	    
		var jsonString = "["+JSON.stringify(cropJson)+"]";
		var postData =  {cropData:jsonString};
		var sendUrl = "controller/crop.htm";
		$.ajax({
		    type: 'POST',
		    context:this,
		    dataType: "json", //lets specify that we will return data as json                  
		    url: sendUrl,
		    data: postData,
		    success: successCrop,
		    error: function() {
		    	//handle error here
		    }
		});
	    }
});





function successCrop(data){
	var uploaderID = $(this).attr("data-uploaderid");
	var form = $("#imageForm_"+uploaderID);
	//si estoy subiendo una nueva imagen
	if(data.image){
		
		$("#uploaded-files_"+uploaderID).empty();
		
		if(data.key == "gallery" || data.key == "header_gal"){
			
			succesGalleryCrop(data,uploaderID);
			
		}else if(data.key == "header" || data.key == "dataType" || data.key == "design"){
			
		$("#uploaded-files_"+uploaderID).append($('<div id="actual_img_'+uploaderID+'" class="actual_img" ><img width="100%"  src="/userimages/'+data.image+'" style="display: block; visibility: visible; width: 400px; height: auto;" /></div>'));
		
		}else if(data.key == "archive"){
			
			succesArchiveCrop(data,uploaderID);
		}
		
		JcropAPI = $('#target_'+uploaderID).data('Jcrop');
		if(JcropAPI){
		JcropAPI.destroy();
		}
		
		$('#progress_'+uploaderID).css('display','none');	
	}
	
	refreshFormData(form);
}

function succesGalleryCrop(data,uploaderID){
	
	$("#gal_table_"+uploaderID).append($('<tr/>',{'id':'img_'+data.id+''}).append($('<td/>').append($('<img/>',{'src':'/userimages/'+data.image,'class':'gallery_image'})))
		       .append($('<td class="text" />').text(data.title))
		       .append($('<td class="icon" />').append($('<button/>',{'class':'btn info alternative icon image edit','data-uploaderid':''+uploaderID+'','data-imgid':''+data.id+'','data-title':''+data.title+'','data-caption':''+data.caption+'','data-url':''+data.url+''})))
			   .append($('<td class="icon" />').append($('<button/>',{'class':'btn danger alternative icon img_gal remove','data-uploaderid':''+uploaderID+'','data-imgid':''+data.id+''})))		
               .append($('<td class="icon" />').append($('<div class="editImage"><span><img class="img_up" src="css/images/arrow-up.png"/><img class="img_down" src="css/images/arrow-down.png"/></span></div>'))));
}

//remove image modal functions
var btn;
$('button.img_gal.remove').live("click", function(){
     btn = this;
     var uploaderID = $(btn).attr('data-uploaderid');
	$("#modal"+uploaderID).modal('show');
	
});

$('#galImgRemove').live("click", function (e) {
	$(".modal-backdrop").remove();
	removeImage();
  	});

//remove image function
function removeImage(){
	var uploaderID = $(btn).attr('data-uploaderid');
	var id = $(btn).attr('data-imgid');
	var form = $("#imageForm_"+uploaderID);
	refreshFormData(form);
    if(id){
	var sendUrl = "controller/deleteGalleryImage.htm";
	var postData =  {image_id:id};
	$.ajax({
	    type: 'POST',
	    context:this,
	    dataType: "text",                   
	    url: sendUrl,
	    data: postData,
	    success: function(data){
	    	var row = $(btn.parentNode.parentNode);
	    	$(row).remove(); // remove row
	    	},
	    error: function() {
	    	//handle error here
	    }
	});
    }
    row =undefined;
}

//edit image function
$('.image.edit').live("click", function(){
	
    var id = $(this).attr('data-imgid');
    var uploaderID = $(this).attr('data-uploaderid');
    $("#imageContainer_"+uploaderID).addClass('editing');
    var form = $("#imageForm_"+uploaderID);
    refreshFormData(form);
    $("#uploaded-files_"+uploaderID).empty();
    if(id){
    $(form).find('input#img_title').val($(this).attr('data-title'));
	document.getElementById("img_text").value=$(this).attr('data-caption');
    $(form).find('input#img_link').val($(this).attr('data-url'));	
    $(form).find('input#img_id').val(id);
    var row = $(this).closest('tr')[0];
    var src = $(row).find('img').attr("src");
    $("#uploaded-files_"+uploaderID).append($('<div id="actual_img_'+uploaderID+'" class="actual_img" ><img width="100%"  src="'+src+'" style="display: block; visibility: visible; width: 400px; height: auto;" /></div>'));
    }
	
});

function refreshFormData(form){
	$(form)[0].reset();
}

//move gallery image down
$('.img_down').live("click", function(){
	
	     var row = $(this).closest('tr')[0];
	     
	     if ($(row).next()){
	    	 var _id1 = $(row).attr('id');
			 var _position1 = $(row).index()+2;
			 var _id2 = $(row).next().attr('id');
			 var _position2 = $(row).next().index();
			 
			 $(row).insertAfter($(row).next());

			 updateImagePosition(_id1,_position1,_id2,_position2);
	     
          }	     
	    
	 });
	 	
//move gallery image up
$('.img_up').live("click", function(){
	
	 var row = $(this).closest('tr')[0];
	 
	    if ($(row).prev()){
	    	
	    	var _id1 = $(row).attr('id');
			var _position1 = $(row).index();
			var _id2 = $(row).prev().attr('id');
			var _position2 = $(row).prev().index()+2;
			 
			$(row).insertBefore($(row).prev());
			 
			updateImagePosition(_id1,_position1,_id2,_position2); 
				
	        
	    }
			
	});


function updateImageData(form,imgData,uploaderID){

	
    sendUrl = "controller/updateGalleryImage.htm";
	var jsonString = "["+JSON.stringify(imgData)+"]";
	var postData =  {Data:jsonString};
	$.ajax({
	    type: 'POST',
	    context:form,
	    dataType: "json", //lets specify that we will return data as json                  
	    url: sendUrl,
	    data: postData,
	    success: function(data){
	    	var tr = $("#img_"+data.id);
			$(tr).find('td.text').text(data.title);
			$(tr).find('button.edit').attr('data-title',data.title);
			$(tr).find('button.edit').attr('data-caption',data.caption);
			$(tr).find('button.edit').attr('data-url',data.url);
			refreshFormData(form);
			$("#uploaded-files_"+uploaderID).empty();
			$("#imageContainer_"+uploaderID).removeClass('editing');
	    },
	    error: function() {
	    	//handle error here
	    }
	});	
	
}

function updateImagePosition(_id1,_position1,_id2,_position2){
	var dataJson  = new Object();
		dataJson.id1 = _id1;
		dataJson.pos1 = _position1;
		dataJson.id2 = _id2;
		dataJson.pos2 = _position2;
	    
		var jsonString = "["+JSON.stringify(dataJson)+"]";
		var postData =  {Data:jsonString};
		var sendUrl = "controller/updateGalleryImagePosition.htm";
		$.ajax({
		    type: 'POST',
		    context:this,
		    dataType: "text", //lets specify that we will return data as json                  
		    url: sendUrl,
		    data: postData,
		    success:function(data){},
		    error: function() {
		    	//handle error here
		    }
		});
}

//abrir file uploader input
$('.uploder_button').live("click", function() { 
	$(this).parent().find('.fileupload').click();
});

